/**
 * IHIS 1.0 by HoneyBread (김민호, 이충희, 이성연, 신경민)
 * SEP 8기 KAIST
 */
package ihis.core.service;

import java.net.InetSocketAddress;

import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.SocketConnector;
import org.apache.mina.transport.socket.nio.SocketConnectorConfig;

/**
 * @author minho kim
 *
 */
public class ServiceClient {
	
	public static synchronized Object serviceCall(String hostName, int serverPort, DefaultIoHandler ioHandlerAdapter)
    throws Exception {
		if(hostName == null || "".equals(hostName)){
			System.out.println("hostName is null");
		}
		if(serverPort == -1){
			System.out.println("severPort is null");
		}
        SocketConnector socketConnector = new SocketConnector();
        socketConnector.setWorkerTimeout(1);

        SocketConnectorConfig socketConnectorConfig = new SocketConnectorConfig();
        socketConnectorConfig.setConnectTimeout(10);
        socketConnectorConfig.getFilterChain().addLast("codec",
            new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
        socketConnectorConfig.getFilterChain().addLast("logger", new LoggingFilter());
        
        System.out.println("call for servcie... hostName:" + hostName + " port:" + serverPort);
        
        ConnectFuture connectFuture = socketConnector.connect(new InetSocketAddress(hostName, serverPort),
            ioHandlerAdapter,
            socketConnectorConfig);
        connectFuture.join();
        
        if (connectFuture.isConnected() == true) {
            while (true) {
                if (ioHandlerAdapter.isFinished()) {
                    connectFuture.getSession().close();
                    return ioHandlerAdapter.getResult();
                }

                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } else {
            throw new Exception("Can't connect server");
        } 
    }
}
